package query;

import java.util.HashMap;
import java.util.Map;

import parser.AST_Describe;
import relop.Schema;

/**
 * Execution plan for describing tables.
 */
class Describe implements Plan {

	protected Schema schema;
	private Catalog catlog = null;
	private Map<Integer, String> typeToTypeStrMap = new HashMap<Integer, String>();

	/**
	 * Optimizes the plan, given the parsed query.
	 * 
	 * @throws QueryException
	 *             if table doesn't exist
	 */
	public Describe(AST_Describe tree) throws QueryException {

		catlog = new Catalog(true); // TODO check true/false
		schema = catlog.getSchema(tree.getFileName());

		typeToTypeStrMap.put(11, "Integer");
		typeToTypeStrMap.put(12, "Float");
		typeToTypeStrMap.put(13, "String");
		

	} // public Describe(AST_Describe tree) throws QueryException

	/**
	 * Executes the plan and prints applicable output.
	 */
	public void execute() {

		if (schema != null) {
			int count = schema.getCount();
			System.out.println(pad("ColName", 20)+pad("ColType",15)+pad("Length", 15));
			System.out.println(pad("-------", 20)+pad("-------",15)+pad("------", 15));
			
			for (int i = 0; i < count; i++) {
				int fieldType = schema.fieldType(i);
				if (typeToTypeStrMap.containsKey(new Integer(fieldType))) {
					System.out.print("\n" + pad(schema.fieldName(i), 20) 
							+ pad(typeToTypeStrMap.get(new Integer(fieldType)), 15)
							+ pad(schema.fieldLength(i)+"", 15));
				} else {
					System.out.print("\n" + pad(schema.fieldName(i), 20) 
							+ pad(fieldType+"", 15)
							+ pad(schema.fieldLength(i)+"", 15));


				}

			}
		}
		// print the output message

	} // public void execute()

	private String pad(String input, int len) {
		int l = input.length();
		String  out = input;
		for (int i = 0; i < len -l ;i++) {
			out = out +" ";
		}
		return out;
	}
} // class Describe implements Plan
